package com.hs.android.fortress.intro;

import com.hs.android.fortress.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class CreateRoomDialogFragment extends DialogFragment {

	public static final String EXTRA_ROOM_NAME = "com.hs.android.fortress.intro.room_name";
	
	private EditText mEditRoom;
	private String mRoomName;
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {

		View v = getActivity().getLayoutInflater().inflate(
				R.layout.fragment_makeroom_dialog, null);

		mEditRoom = (EditText) v.findViewById(R.id.edit_roomname);

		final AlertDialog mAlterDialog = new AlertDialog.Builder(getActivity())
				.setView(v).setPositiveButton(" ", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						mRoomName = mEditRoom.getText().toString();
						
						if(mRoomName.equals("")){
							mRoomName = "Default Room Name";
						}
						
						sendResult(Activity.RESULT_OK);
					}
				}).setNegativeButton(" ", null)
				.create();

		
		mAlterDialog.setOnShowListener(new OnShowListener() {

			@Override
			public void onShow(DialogInterface dialog) {

				Button posBtn = mAlterDialog
						.getButton(AlertDialog.BUTTON_POSITIVE);
				Button navBtn = mAlterDialog
						.getButton(AlertDialog.BUTTON_NEGATIVE);

				setImage(posBtn, R.drawable.btn_roomcreate);
				setImage(navBtn, R.drawable.btn_roomcancel);
			}

			private void setImage(Button btn, int imgId) {
				Drawable drawable = getActivity().getResources().getDrawable(
						imgId);

				btn.setBackgroundDrawable(drawable);

			}
		});

		return mAlterDialog;
	}
	
	private void sendResult(int resultCode){
		if(getTargetFragment() == null)
			return;
		
		Intent i = new Intent();
		i.putExtra(EXTRA_ROOM_NAME, mRoomName);
		
		getTargetFragment()
			.onActivityResult(getTargetRequestCode(), resultCode, i);
	}

}
